/**
 * 获取文件下的元素集合接口测试用例
 *
 * Created by yangyunze on 2021/01/04.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));

const common = require('./../../common');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');
const benchmark = require('./../../../benchmark/analyse-files/cpp');

const fileElements = require('./../../../../phoenix/models/file-elements');

module.exports = describe('/GET files/:id/file-elements.json', function () {
  const administrator = new Administrator();
  let projectVersion = {};
  let otherElementId;
  let testFileId;
  const newUserIds = [];
  function url(fileId) {
    return `/files/${fileId}/file-elements.json`;
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject('c++');
      })
      .then((project) => project.createRandomVersion('c++'))
      .then((res) => {
        projectVersion = res;
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'get');
  common.should.be.tester(uri, url, 'get');

  // 正常请求
  it('it should GET all elements', function (done) {
    projectVersion.getAllFunctions(benchmark)
      .then(([{ fileId }]) => {
        testFileId = fileId;
        const { accessToken } = projectVersion.project.creator.token;
        return new Promise((resolve) => {
          chai.request(uri)
            .get(url(fileId))
            .set('Authorization', `Bearer ${accessToken}`)
            .end((err, res) => {
              res.should.have.status(200);
              common.should.be.elementsMessage(res.body);
              otherElementId = res.body.elements[0].functionId;
              resolve();
            });
        });
      })
      .then(() => {
        done();
      })
      .catch(done);
  });

  // 排序
  const sortByKeys = { elementId: 'functionId' };
  const orders = ['asc', 'desc'];
  const options = [];
  Object.keys(sortByKeys).forEach((sortByKey) => {
    orders.forEach((order) => {
      options.push({ sortBy: sortByKey, order });
    });
  });
  options.forEach(function (option) {
    it(`it should sort elements by ${JSON.stringify(option)}`, function (done) {
      new Promise((resolve) => {
        chai.request(uri)
          .get(url(testFileId))
          .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
          .query(option)
          .end((err, res) => {
            res.should.have.status(200);
            common.should.be.elementsMessage(res.body);
            res.body.elements.should.be.sortedBy(sortByKeys[option.sortBy], option.order === 'desc');
            resolve();
          });
      })
        .then(() => {
          done();
        })
        .catch(done);
    });
  });

  // test kinds parameter
  const kindsGroup = [
    [fileElements.elementKind.namespace],
    [fileElements.elementKind.function, fileElements.elementKind.functionUnderTemplate],
  ];
  kindsGroup.forEach((kinds) => {
    it(`it should get all elements with kinds ${kinds.join(',')}`, function (done) {
      new Promise((resolve) => {
        chai.request(uri)
          .get(url(testFileId))
          .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
          .query({ kinds })
          .end((err, res) => {
            res.should.have.status(200);
            common.should.be.elementsMessage(res.body);
            res.body.elements.forEach((element) => {
              element.kind.should.be.oneOf(kinds);
            });
            resolve();
          });
      })
        .then(() => {
          done();
        })
        .catch(done);
    });
  });

  // 不可获取不存在文件的元素
  it('it should fail to get elements when the file is not exists', function (done) {
    new Promise((resolve) => {
      chai.request(uri)
        .get(url('000000000000000000000000'))
        .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
        .end((err, res) => {
          res.should.have.status(404);
          common.should.be.errorMessage(res.body);
          resolve();
        });
    })
      .then(done)
      .catch(done);
  });

  // 不可获取他人项目文件的元素列表
  it('it should fail to get elements when the project is not yours', function (done) {
    let newUser;
    administrator.createRandomTester()
      .then((newTester) => {
        newUserIds.push(newTester.userId);
        newUser = newTester;
        return newTester.getToken();
      })
      .then(() => {
        chai.request(uri)
          .get(url(otherElementId))
          .set('Authorization', `Bearer ${newUser.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });
});
